package middleware

import (
	"gin-worked/work"
	"github.com/gin-gonic/gin"
	"strings"
)

func GetParamMiddleware(c *gin.Context) {

	method := c.Request.Method
	// 创建一个map来存储自定义数据
	customDataMap := make(map[string]string)
	if method == "GET" {
		query := c.Request.URL.Query()
		for index, param := range query {
			value := strings.Join(param, " ")
			customDataMap[index] = value
		}
	} else if method == "POST" {
		ContentType := c.Request.Header.Get("Content-Type")

		if ContentType == "application/json" || ContentType == "application/json;charset=UTF-8" || ContentType == "application/x-www-form-urlencoded" {
			str := make(map[string]string)
			var err error
			if ContentType == "application/x-www-form-urlencoded" {
				err = c.ShouldBind(&str)
			} else {
				err = c.BindJSON(&str)
			}

			if err != nil {
				work.ReturnResult(c, 0, "获取参数失败", "")
				c.Abort()
				return
			}
			customDataMap = str
		} else {
			queryParams, _ := c.MultipartForm() //暂时只支持post
			if queryParams != nil {
				// 组装自定义数据
				for index, param := range queryParams.Value {
					value := strings.Join(param, " ")
					customDataMap[index] = value
				}
			}
		}
	}
	c.Set("params", customDataMap)
	c.Next()
}
